<?php
namespace app\admin\controller;
use app\common\model;
use app\service\LogService;
use EasyWeChat\Factory;
use EasyWeChat\OpenPlatform\Server\Guard;
use think\Controller;
use app\service\MsgService;

class Open extends Base
{   
    public $openPlatform;
    public function __construct () {
        parent::__construct();
        $config = [
            'app_id'   => config('open_appid'),
            'secret'   => config('open_secret'),
            'token'    => config('open_token'),
            'aes_key'  => config('open_aeskey'),
            'response_type' => 'array'
        ];
        $this->openPlatform = Factory::openPlatform($config);
    }

    /* 发起授权 */
    public function auth () {
        $res = $this->openPlatform->getPreAuthorizationUrl(getDomain().'/admin/open/callback');
        return returnJson(0,'',$res);
        echo "<a href='{$res}'>授权</a>";
    }

    public function callback () {

        $Authorize = $this->openPlatform->handleAuthorize();
        $Authorizer = $this->openPlatform->getAuthorizer($Authorize['authorization_info']['authorizer_appid']);
        $mallInfo = [
            'authorizer_appid' => $Authorize['authorization_info']['authorizer_appid'],
            'authorizer_access_token' => $Authorize['authorization_info']['authorizer_access_token'],
            'authorizer_refresh_token' => $Authorize['authorization_info']['authorizer_refresh_token'],
            'detail' => json_encode($Authorizer['authorizer_info'])
        ];
        
        if($this->mall['authorizer_appid'] && $this->mall['authorizer_appid']!=$mallInfo['authorizer_appid']) {
            _pr('该公众号与之前授权信息不一致');
        }
        $oldMall = $this->mallModel->update($mallInfo,[
            'id' => $this->mall['id']
        ]);
        //配置模板消息
        MsgService::S([
            'mall_id' => $this->mall['id']
        ])->resetMallTmpl($this->mall['id']);
        header('Location: /w/#/pages/config/wechat');
        /* {
            "nick_name":"中科华标",
            "head_img":"http://wx.qlogo.cn/mmopen/AtUZ4ciama3yK6pEqeCN74nC1vjkXjt3CCk0B9GtE9HC4jN44ItD4dYLe3CCA3XPbkribxEhsRibu8FtCVJy1yrVsTs9LiaypEWa/0",
            "service_type_info":{
            "id":2
            },
            "verify_type_info":{
            "id":0
            },
            "user_name":"gh_92f3adc93a69",
            "alias":"huabiao100",
            "qrcode_url":"http://mmbiz.qpic.cn/mmbiz_jpg/Zgljdp7hsMEOzyDSp3dPEElFSARHJNhXbVzAg14MZgX3vfUmDz41W9fy1uEicictluJDSa1e5tX8aBfoVCTwLPug/0",
            "business_info":{
            "open_pay":1,
            "open_shake":0,
            "open_scan":0,
            "open_card":0,
            "open_store":1
            },
            "idc":1,
            "principal_name":"哇哦科技(上海)有限公司",
            "signature":"中科华标科技有限公司旗下公众号；专注于为餐饮、教育培训、贸易、制造等行业提供最前沿的移动互联网+落地解决方案, 做互联网+的最佳实践者。"
            } 
        */
    }

    public function resetTmpl () {
        MsgService::S([
            'mall_id' => $this->mall['id']
        ])->resetMallTmpl($this->mall['id']);
    }

    /* 接收ticket */
    public function ticket () {
        //file_put_contents(ROOT_PATH.'log.txt',json_encode(input()).PHP_EOL,FILE_APPEND);
        $server = $this->openPlatform->server;
        $server->push(function ($message) {
            //file_put_contents(ROOT_PATH.'log.txt','EVENT_AUTHORIZED'.json_encode($message).PHP_EOL,FILE_APPEND);
        }, Guard::EVENT_AUTHORIZED);
        $server->push(function ($message) {
            //file_put_contents(ROOT_PATH.'log.txt','EVENT_UPDATE_AUTHORIZED'.json_encode($message).PHP_EOL,FILE_APPEND);
        }, Guard::EVENT_UPDATE_AUTHORIZED);
        $server->push(function ($message) {
            //file_put_contents(ROOT_PATH.'log.txt','EVENT_UNAUTHORIZED'.json_encode($message).PHP_EOL,FILE_APPEND);
        }, Guard::EVENT_UNAUTHORIZED);
        return $server->serve()->send();
    }
}
